package com.heima.article.interceptor;

import com.heima.common.entity.User;
import com.heima.common.util.AppThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class MediaInterceptor implements HandlerInterceptor {
    /**
     *前置
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        获取请求头
        String userId = request.getHeader("userId");
//        判断是否为空
        if (!StringUtils.isEmpty(userId)){
//            不为空，将userId存入线程中
            User user = new User();
            user.setUserId(Integer.parseInt(userId));
            AppThreadLocal.set(user);

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            AppThreadLocal.remove();
    }
}
